#-*- coding: utf-8 -*-
import json
import uuid
import time
from locust import TaskSet, HttpLocust, task
import hashlib
#pip install mlogging
import base64

import logging

privat_H2_url = 'http://127.0.0.1:8801/TTSH2Service/onHttpRequest'  #  树勇 h2 service
#privat_H2_url = 'http://127.0.0.1:8801/HttpService'                 #博森  h1 service
argsGateWay = 0


#虚拟用户所执行任务
class UserBehavior(TaskSet):

    #并发用户可以重复使用数据
    def on_start(self):  #初始化工作
        print("onStart")
        self.txt = "读书可以供我们消遣娱乐，可以装饰，也能够增加才干。为消遣而读书，常常是在独处退居之时；为装饰而读书，多见于高谈阔论之中；为增长才干而读书，是为了在社会中"
        self.ServiceParam = {
            'platform': 'Linux',
            'version': '0.0.0.1',
            'parameters': {
                'tte': '1',  #1:UTF-8 (目前仅支持UTF-8格式)
                'tim': '0',  # // 0：女声 1：男声
                'aue': '1',  #音频格式，0-wav，1-pcm，2-opus，3-mp3
                'tt': '0',  #// 文本格式,  0：文本 1：SSML
                'sp': '1.0',  #// 语速 [0.5, 2.0] wav和pcm支持4k到24k的采样率
                'sr': '16000',  #  // 采样率 opus支持8k 12k 16k 和24k的采样率
                'vol': '2.0'  # // 音量[0.1, 10.0]
            }
        }

        self.headers = {
            'Service-Type': 'synthesis',
            'Application-Id': 'd1bd6e9f-8dbf-4ea6-b92f-75dfa263304c',  # test
            'Request-Id': str(uuid.uuid1()),
            'Sequence-Id': str(1),
            'Protocol': str(1),
            'Net-State': str(2),
            'Applicator': str(0),
            'Host': 'aiapi.jd.com',  # neuhub的服务器
            'Property': json.dumps(self.ServiceParam)
        }

    def createURL(self):
        appkey = 'b148a7f7cc27a4f336e75c83a3ada768'
        sectetkey = 'c92d4ebd0d21a198af18bc53d7524eda'
        m = hashlib.md5()
        nowTime = int(time.time() * 1000)
        before = sectetkey + str(nowTime)
        m.update(before.encode('utf8'))
        params = {'appkey': appkey, 'timestamp': nowTime, 'sign': m.hexdigest()}
        if argsGateWay > 0:  #走neuhub 网关
            url = '?'.join([neuhub_H2_url, urlencode(params)])
        else:
            url = privat_H2_url

    #logging.info('srvURL=%s' % url)
        return url

    @task
    def postTask(self):
        print("postTask")
        seq = 1
        buf = bytearray()
        ret = ''
        result = {}
        self.headers['Request-Id'] = str(uuid.uuid1())
        while True:
            #try:
            self.headers['Sequence-Id'] = str(seq)
            logging.info('post:reqID=%s, seqID=%d, txt=%s',
                         self.headers['Request-Id'], seq, self.txt)
            startTime = time.time()
            r = self.client.post(self.createURL(),
                                 data=self.txt.encode('utf-8'),
                                 headers=self.headers)
            endTime = time.time()

            #logging.info("http code=%d", r.status_code)
            if r.status_code == 200:
                result = json.loads(r.content)
                if argsGateWay > 0 and result[
                        'code'] != '10000':  # NeuHub response
                    ret = 'ERROR:getway code error! code:%s' % (result['code'])
                    logging.error(ret)
                    break

                result = result[
                    'result'] if argsGateWay > 0 else result  # TTS Service Reponse
                status = result['status']
                retReqID = result['request_id']
                retSeqID = result['index']
                delay = round(endTime - startTime, 4)

                if status == 0:
                    audioData = ''
                    #logging.error(result['audio'])

                    retProgress = result['progress']
                    audioLen = len(result['audio'])
                    ret = 'SUCCEED[%d]:req=%s, seq=%s, progress=%s, delay=%4lf' % (
                        status, retReqID, retSeqID, retProgress, delay)
                    logging.info(ret)
                    if retSeqID < 0:
                        break
                    seq += 1
                else:
                    ret = 'ERROR[%d]:req=%s, seq=%s, text:%s' % (
                        status, retReqID, retSeqID, self.txt)
                    logging.error(ret)
                    break
            else:
                ret = 'ERROR:code:%d' % r.status_code
                logging.error(ret)
                return
            #except Exception as e:
            #    logging.error(traceback.print_exec())
            #    return


#代表每个并发里面的每个用户
class WebsiteUser(HttpLocust):
    host = "http://127.0.0.1:8801/HttpService"  #默认服务器 URL
    task_set = UserBehavior
    min_wait = 0  # 每个任务之间等待的最小时间
    max_wait = 0  # 每个任务之间等待的最大时间
